package org.numb.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.numb.model.Address;
import org.numb.model.User;

public class UserValidator implements ConstraintValidator<UserValid, User> {

    private String prefix = "";

    private final int MIN = 10;

    @Override
    public void initialize(UserValid userValid) {
        // 初始化可以从注解中获取值
        prefix = userValid.prefix();
    }

    @Override
    public boolean isValid(User user, ConstraintValidatorContext context) {
        // user为null时跳过校验，返回true
        if (user == null) {
            return true;
        }
        boolean isValid = false;
        if (user.getId() != null && user.getAddress() != null) {
            String id = user.getId();
            Address address = user.getAddress();
            if (id.length() > MIN) {
                isValid = address.getCity().startsWith(prefix);
            }
        }
        if (!isValid) {
            String messageTemplate = context.getDefaultConstraintMessageTemplate();
            context.buildConstraintViolationWithTemplate(messageTemplate).addConstraintViolation()
                .disableDefaultConstraintViolation();
        }
        return isValid;
    }
}
